package com.quick.proxy.core.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.quick.proxy.core.CmdTypeConstants;
import com.quick.proxy.core.ForwardMessage;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * Description: 响应工具类
 * Author: 吃素不吃肉
 * Date: 2023/7/4
 *
 * @author 吃素不吃肉
 */
@Slf4j
public class ResponseUtils {

    public static void success(Channel channel, int cmdType, Object data) {
        Map<String, Object> proxyResponse = new HashMap<>(3);
        proxyResponse.put("code", "200");
        proxyResponse.put("msg", "success");
        proxyResponse.put("data", data);
        channel.writeAndFlush(ProtocolUtils.getByte(cmdType, JSONUtil.toJsonStr(proxyResponse).getBytes(StandardCharsets.UTF_8)));
    }

    public static void fail(Channel channel, int cmdType, String msg) {
        Map<String, Object> proxyResponse = new HashMap<>(2);
        proxyResponse.put("code", "403");
        msg = StrUtil.isEmpty(msg) ? "fail" : msg;
        proxyResponse.put("msg", msg);
        log.warn("{}", msg);
        channel.writeAndFlush(ProtocolUtils.getByte(cmdType, JSONUtil.toJsonStr(proxyResponse).getBytes(StandardCharsets.UTF_8)));
        channel.close();
    }

    /**
     * 拒绝连接
     *
     * @param visitorId 访问者id
     * @param channel   代理通道
     */
    public static void disabledConnect(String visitorId, Channel channel) {
        ForwardMessage forwardMessage = new ForwardMessage();
        forwardMessage.setVisitorId(visitorId);
        if (channel.isOpen() && channel.isActive()) {
            channel.writeAndFlush(ProtocolUtils.getByte(CmdTypeConstants.DISABLED_CONNECT, JSONUtil.toJsonStr(forwardMessage).getBytes(StandardCharsets.UTF_8)));
        }
    }

    /**
     * 连接
     *
     * @param visitorId              访问者id
     * @param realProxyClientAddress 真实地址
     * @param channel                代理通道
     */
    public static void connect(String visitorId, String realProxyClientAddress, Channel channel) {
        ForwardMessage forwardMessage = new ForwardMessage();
        forwardMessage.setVisitorId(visitorId);
        forwardMessage.setBytes(realProxyClientAddress.getBytes(StandardCharsets.UTF_8));
        if (channel.isOpen() && channel.isActive()) {
            channel.writeAndFlush(ProtocolUtils.getByte(CmdTypeConstants.CONNECT, JSONUtil.toJsonStr(forwardMessage).getBytes(StandardCharsets.UTF_8)));
        }
    }
}
